<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="bannerTitle">
        <el-input
          v-model="queryParams.bannerTitle"
          placeholder="请输入标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="banner类型" prop="bannerType" label-width="90px">
        <el-select v-model="queryParams.bannerType" placeholder="请选择banner类型" clearable size="small">
          <el-option
            v-for="dict in bannerTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="商品分类" prop="goodsType">-->
      <!--        <el-select v-model="queryParams.goodsType" placeholder="请选择商品分类" clearable size="small">-->
      <!--          <el-option label="请选择字典生成" value="" />-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['app:banner:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['app:banner:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['app:banner:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['app:banner:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bannerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" type="index" width="50" align="center">
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="bannerTitle"/>
      <el-table-column label="排序" align="center" prop="bannerSort"/>
      <el-table-column label="图片" align="center" width="80" prop="imgUrl">
        <template scope="scope">
          <el-popover placement="right" title="" trigger="hover">
            <img :src="baseUrl + scope.row.imgUrl" style="width: auto;">
            <img slot="reference" :src="baseUrl + scope.row.imgUrl" :alt="baseUrl + scope.row.imgUrl"
                 style="max-height: 50px;max-width: 130px">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="banner类型" align="center" prop="bannerType" :formatter="bannerTypeFormat"/>
      <el-table-column label="跳转类型" align="center" prop="jumpType" :formatter="jumpTypeFormat"/>
      <el-table-column label="跳转标识" align="center" prop="banner_code" :formatter="bannerCodeFormat"/>
      <el-table-column label="广告状态" align="center" prop="navigateStatus">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.bannerStatus" active-value="1" inactive-value="0"
                     @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <!--      <el-table-column label="商品分类" align="center" prop="goodsType" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['app:banner:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['app:banner:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改APP端banner图对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="550px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="标题" prop="bannerTitle">
          <el-input v-model="form.bannerTitle" placeholder="请输入标题"/>
        </el-form-item>
        <el-form-item label="排序" prop="bannerSort">
          <el-input-number v-model="num" @change="handleChange" :min="1" :max="100" label="排序"></el-input-number>
        </el-form-item>
        <el-form-item label="banner类型" prop="bannerType">
          <el-select v-model="form.bannerType" placeholder="请选择banner类型">
            <el-option
              v-for="dict in bannerTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="跳转类型" prop="jumpType">
          <el-select v-model="form.jumpType" placeholder="请选择跳转类型" @change="jumpTypChange">
            <el-option
              v-for="item in jumpTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="广告状态" prop="bannerStatus">
          <el-select v-model="form.bannerStatus" placeholder="请选择广告状态">
            <el-option
              v-for="item in bannerStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="内部标识" prop="bannerCode" v-if="form.jumpType=='1'">
          <el-select v-model="form.bannerCode" placeholder="请选择内部跳转标识">
            <el-option
              v-for="dict in bannerCodeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="链接" prop="bannerHref" v-if="form.jumpType=='2'">
          <el-input v-model="form.bannerHref" placeholder="请输入链接"/>
        </el-form-item>
        <el-form-item label="banner图">
          <el-upload
            class="avatar-uploader"
            :action="upload.url"
            :show-file-list="false"
            :headers="upload.headers"
            name="file"
            accept=".jpg, .png"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
        <!--        <el-form-item label="商品分类" prop="goodsType">-->
        <!--          <el-select v-model="form.goodsType" placeholder="请选择商品分类">-->
        <!--            <el-option label="请选择字典生成" value="" />-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { getToken } from '@/utils/auth'
  import {
    listBanner,
    getBanner,
    delBanner,
    addBanner,
    updateBanner,
    exportBanner,
    changeBannerStatus
  } from '@/api/app/banner'

  export default {
    name: 'Banner',
    components: {},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        num: 1,
        // APP端banner图表格数据
        bannerList: [],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        // baseUrl: process.env.VUE_APP_BASE_API,
        baseUrl: 'https://youhuiniu.oss-cn-beijing.aliyuncs.com/',
        imageUrl: '',
        // 上传参数
        upload: {
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: { Authorization: 'Bearer ' + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + '/common/upload',
          // 上传的文件列表
          fileList: []
        },
        // banner类型(1首页，2个人中心，3商品)字典
        bannerTypeOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          bannerTitle: null,
          bannerType: null,
          goodsType: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          bannerTitle: [
            { required: true, message: '标题不能为空', trigger: 'blur' }
          ],
          bannerSort: [
            { required: true, message: '排序不能为空', trigger: 'blur' }
          ]
        },
        //跳转类型
        jumpTypeOptions: [{ value: '0', label: '不跳转' }, { value: '1', label: '内部跳转' }, { value: '2', label: '外部跳转' }],
        bannerStatusOptions: [{ value: '1', label: '启用' }, { value: '0', label: '禁用' }],
        bannerCodeOptions:[]
      }
    },
    created() {
      this.getList()
      this.getDicts('app_banner_type').then(response => {
        this.bannerTypeOptions = response.data
      })
      this.getDicts('app_banner_code').then(response => {
        this.bannerCodeOptions = response.data
      })
    },
    methods: {
      /** 查询APP端banner图列表 */
      getList() {
        this.loading = true
        listBanner(this.queryParams).then(response => {
          this.bannerList = response.rows
          this.total = response.total
          this.loading = false
        })
      },
      // banner类型(1首页，2个人中心，3商品)字典翻译
      bannerTypeFormat(row, column) {
        return this.selectDictLabel(this.bannerTypeOptions, row.bannerType)
      },
      bannerCodeFormat(row, column) {
        return this.selectDictLabel(this.bannerCodeOptions, row.bannerCode)
      },
      jumpTypeFormat(row, column) {
        let jumpType = this.jumpTypeOptions.find(item => item.value == row.jumpType)
        if (jumpType) {
          return jumpType.label
        } else {
          return '无'
        }
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset() {
        this.form = {
          bannerId: null,
          bannerTitle: null,
          imgUrl: null,
          bannerSort: null,
          bannerType: null,
          goodsType: null,
          bannerStatus: null,
          jumpType: null,
          bannerHref: null,
          bannerCode: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null
        }
        this.num = 1
        this.imageUrl = ''
        this.resetForm('form')
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm('queryForm')
        this.handleQuery()
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.bannerId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset()
        this.open = true
        this.title = '添加banner图'
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset()
        const bannerId = row.bannerId || this.ids
        getBanner(bannerId).then(response => {
          this.form = response.data
          this.open = true
          this.title = '修改banner图'
          this.num = this.form.bannerSort
          this.imageUrl = this.baseUrl + this.form.imgUrl
        })
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.form.bannerId != null) {
              updateBanner(this.form).then(response => {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              })
            } else {
              addBanner(this.form).then(response => {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              })
            }
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const bannerIds = row.bannerId || this.ids
        this.$confirm('是否确认删除该条数据?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return delBanner(bannerIds)
        }).then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams
        this.$confirm('是否确认导出所有数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return exportBanner(queryParams)
        }).then(response => {
          this.download(response.msg)
        })
      },
      handleAvatarSuccess(res, file) {
        this.form.imgUrl = res.data.objectID

        this.imageUrl = res.data.url
      },
      beforeAvatarUpload(file) {
        const isLt5M = file.size / 1024 / 1024 < 5
        if (!isLt5M) {
          this.$message.error('上传头像图片大小不能超过 5MB!')
        }
        return isLt5M
      },
      handleChange(value) {
        this.form.bannerSort = value
      },
      jumpTypChange(jumpType) {
        if (jumpType == '1') {
          this.form.bannerHref = ''
        }
        if (jumpType == '2') {
          this.form.bannerCode = ''
        }
      },
      // 启用禁用状态修改
      handleStatusChange(row) {
        changeBannerStatus(row.bannerId, row.bannerStatus)
        this.msgSuccess('操作' + this.$t('constant.success'))
      }
    }
  }
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
